﻿using Microsoft.AspNetCore.Mvc;
//using NodaTime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using T.ServiceComponent.Kernel.Service;
using Microsoft.AspNetCore.Http;
using HttpContext = Microsoft.AspNetCore.Http.HttpContext;

namespace T.FAS.Runtime.MF.SGPlugin
{
    public class MicroflowEventStreamService
    {
        private readonly List<EventStreamWriter> _connectedClients = new();
        private readonly object _lock = new();
        public async Task TestGetSSEService()
        {
            // 设置 SSE 响应头
            T.ServiceComponent.Kernel.Service.HttpContext.Current.Response.Headers.Add("Content-Type", "text/event-stream");
            T.ServiceComponent.Kernel.Service.HttpContext.Current.Response.Headers.Add("Cache-Control", "no-cache");
            T.ServiceComponent.Kernel.Service.HttpContext.Current.Response.Headers.Add("Connection", "keep-alive");
            T.ServiceComponent.Kernel.Service.HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            // 创建事件流写入器
            var streamWriter = new EventStreamWriter(T.ServiceComponent.Kernel.Service.HttpContext.Current.Response.Body);
            lock (_lock)
            {
                _connectedClients.Add(streamWriter);
            }

            try
            {
                // 获取正确的取消令牌（.NET 9 方式）
                var cancellationToken = new CancellationTokenSource();
                // 发送初始连接确认
                await streamWriter.WriteEventAsync("connected", "{\"status\":\"OK\"}");

                // 保持连接打开
                while (!cancellationToken.IsCancellationRequested)
                {
                    // 检查连接是否活跃
                    if (!await streamWriter.IsConnectionAlive())
                    {
                        break;
                    }

                    // 发送心跳保持连接
                    await streamWriter.WriteEventAsync("heartbeat", $"{{\"time\":\"{DateTime.UtcNow:O}\"}}");

                    // 等待1秒
                    await Task.Delay(1000, cancellationToken.Token);
                }
            }
            catch (TaskCanceledException)
            {
                // 客户端断开连接 - 正常退出
            }
            catch (Exception ex)
            {
                Console.WriteLine($"SSE Error: {ex.Message}");
            }
            finally
            {
                lock (_lock)
                {
                    _connectedClients.Remove(streamWriter);
                }
                streamWriter.Dispose();
            }
        }
        //// 向所有客户端广播消息
        //[HttpPost("broadcast")]
        //public async Task<IActionResult> BroadcastMessage([FromBody] string message)
        //{
        //    List<EventStreamWriter> clients;
        //    lock (_lock)
        //    {
        //        clients = new List<EventStreamWriter>(_connectedClients);
        //    }

        //    var tasks = new List<Task>();
        //    foreach (var client in clients)
        //    {
        //        tasks.Add(client.WriteEventAsync("broadcast", $"{{\"message\":\"{message}\"}}"));
        //    }

        //    await Task.WhenAll(tasks);
        //    return Ok(new { clients = clients.Count });
        //}
    }
    // SSE 事件流写入辅助类
    public sealed class EventStreamWriter : IDisposable
    {
        private readonly Stream _responseBody;
        private readonly UTF8Encoding _encoder = new();

        public EventStreamWriter(Stream responseBody)
        {
            _responseBody = responseBody;
        }

        public async Task WriteEventAsync(string eventType, string data)
        {
            try
            {
                // 根据 SSE 格式规范构建消息
                var eventBuilder = new StringBuilder();
                if (!string.IsNullOrEmpty(eventType))
                    eventBuilder.Append($"event: {eventType}\n");

                eventBuilder.Append($"data: {data}\n\n");

                var bytes = _encoder.GetBytes(eventBuilder.ToString());
                await _responseBody.WriteAsync(bytes);
                await _responseBody.FlushAsync();
            }
            catch
            {
                // 写入失败（客户端已断开）
            }
        }

        public async Task<bool> IsConnectionAlive()
        {
            try
            {
                // 尝试发送空操作保持连接
                await _responseBody.WriteAsync(Array.Empty<byte>());
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void Dispose()
        {
            try
            {
                _responseBody.Dispose();
            }
            catch
            {
                // 忽略处置异常
            }
        }
    }
}